package logic

import (
	"context"
	"encoding/json"
	"furni-net/cache"
	"furni-net/furnirpc/furnirpc"
	"furni-net/furnirpc/internal/svc"
	modelsni "furni-net/models"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ToolListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewToolListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ToolListLogic {
	return &ToolListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ToolListLogic) ToolList(in *furnirpc.ToolListRequest) (*furnirpc.ToolListResponse, error) {
	// todo: add your logic here and delete this line
	key := "ToolList"
	var toolDatas []modelsni.ToolData
	var toollists []*furnirpc.ToolList
	cachejson, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if cachejson == "" {
		modelsni.DB.Debug().
			Table("tools").
			Joins("left join classes on tools.class_id=classes.id").
			Joins("left join brands on tools.brand_id=brands.id").
			Select("tools.*",
				"classes.name as ClassName",
				"brands.name as BrandName").
			Find(&toolDatas)
		cachedata, _ := json.Marshal(toolDatas)
		cache.Rdb.Set(cache.Ctx, key, cachedata, time.Hour*1)
	} else {
		json.Unmarshal([]byte(cachejson), &toolDatas)
	}
	for _, data := range toolDatas {
		list := &furnirpc.ToolList{
			Name:      data.Name,
			Price:     float32(data.Price),
			Num:       int64(data.Num),
			Img:       data.Img,
			Info:      data.Info,
			ClassName: data.ClassName,
			BrandName: data.BrandName,
			ToolId:    int64(data.ID),
		}
		toollists = append(toollists, list)
	}
	return &furnirpc.ToolListResponse{
		List: toollists,
	}, nil
}
